package com.itheima.service.impl;


import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.dao.MenuDao;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.pojo.Menu;
import com.itheima.service.MenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;

import java.util.List;

@Service(interfaceClass = MenuService.class)
public class MenuServiceImpl implements MenuService {


    @Autowired
    private MenuDao menuDao;

    @Override
    public List<Integer> findMenuIdsByRoleId(int id) {
        return menuDao.findMenuIdsByRoleId(id);

    }

    @Override
    public void add(Menu menu) {
        Integer parentMenuId = menu.getParentMenuId();
        menuDao.add(menu);
        Integer id = menu.getId();
        if (parentMenuId != null) {
            menuDao.addLevel(2, id);
        } else {
            menuDao.addLevel(1, id);
        }
    }

    @Override
    public PageResult<Menu> findPage(QueryPageBean queryPageBean) {
        //实现模糊查询，拼接%
        if(!StringUtils.isEmpty(queryPageBean.getQueryString())){
            queryPageBean.setQueryString("%"+queryPageBean.getQueryString()+"%");
        }
        //开始分页
        PageHelper.startPage(queryPageBean.getCurrentPage(),queryPageBean.getPageSize());
        Page<Menu> page = menuDao.findByCondition(queryPageBean.getQueryString());
        //返回封装的结果
        PageResult<Menu> pageResult = new PageResult<>(page.getTotal(), page.getResult());
        return pageResult;
    }

    @Override
    public void update(Menu menu) {
        menuDao.update(menu);
    }

    @Override
    public List<Menu> findAll() {
        return menuDao.findAll();
    }

    @Override
    public List<Integer> getParentMenuIds() {
        return menuDao.getParentMenuIds();
    }

    @Override
    public void deleteById(Integer id) {
        List<Menu> list=menuDao.findSunMenuByParentMenuId(id);
        if (list!=null){
            for (Menu menu : list) {
                Integer sunMenuId = menu.getId();
                menuDao.deleteById(sunMenuId);
            }
        }
        menuDao.deleteById(id);
    }

    @Override
    public Menu findById(int id) {
        return menuDao.findById(id);
    }

}
